#include<reg52.h>

sbit ledr=P2^0;
sbit ledg=P2^2;
sbit ledy=P2^3;


sbit btnr=P3^2;
sbit btng=P3^3;

sbit emax=P3^7;


unsigned char sata=0;				 //接收数据
unsigned char addr=0;	
unsigned char flag=0;	
unsigned char swit=1;
unsigned char opt=0;	
unsigned char detime=0;



void init ()
{
	P1=0xff;
	addr=((~P1&0xf0)>>4)*10+(~P1&0x0f);
	emax=1;
	ledr=1;
	ledg=1;
	ledy=1;

	TMOD=0x21;
	TH1=0xfd;
	TL1=0xfd;
	TL0=0x00;
	TH0=0xEE;

	
	SM0=0;
	SM1=1;
	EA=1;
	ES=1;
	

	EX0=1;
	EX1=1;
	ET0=1;
	IT0=1;
	IT1=1;
	TR1=1;

	
	REN=1;			 	
}



void de(unsigned int a )
{
	int i;
	while(a--)
	{
		for(i=0;i<120;i++);
	}
}

void send(state)	   //发送串行数据函数
{	
	
		emax=0;
		de(1);
		SBUF=state;			   //发送串口数据
		while(!TI);
		TI=0;
		emax=1;	
		flag=0;	
		return;
	
}




void int0()	interrupt 0			  //外部中断由清除按钮触发
{	
	if (swit){
		opt=1;
		sata=0x80;
		ledg=1;
		ledr=0;
		ledy=1;
	}
	

}

void int1() interrupt 1
{
	
	TL0=0x00;
	TH0=0xEE;
	detime+=1;
	if (detime==addr*2){
		TR0=0;
		detime=0;
		send(addr);
		send(sata);
		send(addr^sata);
	}else{}
}

void int2()	interrupt 2			  //外部中断由清除按钮触发
{	
	if (swit){
		opt=1;
		sata=0xf0;
		ledg=0;
		ledr=1;
		ledy=1;
	}
	
}




void receive() interrupt 4	  //串口中断函数
{
	unsigned char n;
	if(RI){
		RI=0;
	}else{return;}
	
	n=SBUF;
	if(n==addr){
		flag=1;
	}else if(flag==1){
		if(n==0xf0){
			swit=1;
			sata=0xf0;
			ledg=0;
			ledr=1;
			ledy=1;
			send(sata);
		}else if(n==0x8f){
			swit=1;
			sata=0x8f;
			ledg=1;
			ledr=1;
			ledy=0;
			send(sata);
		}else if (n==0xcc){
			swit=0;
			ledg=1;
			ledr=1;
			ledy=1;
			send(0xcc);
		}else{
			send(sata);
		}
	}else if((n==0x99)&&opt){
		opt=0;
		TR0=1;
	}else{}

		
}
void main()
{	
	
	init();
	while(1)
	{
		
			
	}
}
